package sh.wnxy.wn38.controller;


import com.alipay.api.internal.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import sh.wnxy.wn38.entity.Cart;
import sh.wnxy.wn38.entity.Order;
import sh.wnxy.wn38.entity.Orderitem;
import sh.wnxy.wn38.entity.User;
import sh.wnxy.wn38.service.*;
import sh.wnxy.wn38.service.vo.dingdan;
import sh.wnxy.wn38.utils.Result;
import sh.wnxy.wn38.utils.vo.fakeCart;

import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wn38
 * @since 2021-07-13
 */
@CrossOrigin
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    IOrderService iOrderService;
    @Autowired
    IOrderitemService iOrderitemService;
    @Autowired
    ITicketService iTicketService;
    @Autowired
    ISpotService iSpotService;
    @Autowired
    ICartService iCartService;
    IUserService us;
    @Autowired
    public void setUs(IUserService us) {
        this.us = us;
    }
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("生成订单保存数据库")
    @PostMapping("/AddOrder")
    public Result addOrder(@RequestBody List<fakeCart> fakeCartList) {
        UUID uuid = UUID.randomUUID();
        Double s = 0.0;
        String userId  = "";
        int i = 1;
        System.out.println(111);
        Map<Integer, Orderitem> orderList = new HashMap<>();
        for (fakeCart cart : fakeCartList) {
            LocalDate date = cart.getDateTime();
            System.out.println(date);
            String kind = cart.getKind();
            System.out.println(kind);
            Integer number = cart.getNumber();
            String path = cart.getPath();
            Double price = cart.getPrice();
            String spotName = cart.getSpotName();
            Integer cartId = cart.getCartId();
            if(cartId!=null){
                boolean b = iCartService.removeById(cartId);
            }
            userId = cart.getUserId();
            System.out.println(userId);
            Integer id = iSpotService.findByname(spotName);
            Integer result = iTicketService.subnum(date, id, kind, number);
            if(result!=0){
                Orderitem orderitem = new Orderitem();
                orderitem.setOiStatus("0");
                orderitem.setOiSpotname(spotName);
                orderitem.setOiNum(number);
                orderitem.setOiSpottype(kind);
                Double total = price * number;
                orderitem.setOiTotal(total);
                orderitem.setOiSpotdate(date);
                orderitem.setOiImg(path);
                orderitem.setOiSpotprice(price);
                orderitem.setOiOrderid(uuid + "");
                s += total;
                orderList.put(i, orderitem);
                i++;
                System.out.println(111111111);
                boolean result1 = iOrderitemService.save(orderitem);
            }
        }
        Order order = new Order();
        String orderId = uuid + "";
        order.setOrderId(orderId);
        order.setOrderSum(s);
        order.setOrderUserid(userId);
        System.out.println(order);
        boolean result=iOrderService.save(order);
        if(fakeCartList.get(0).getCartId()!=null) {
            return Result.ok().data("orderId", orderId).msg("购物车跳转");
        }else{
            return Result.ok().data("orderId",orderId).msg("立即购买跳转");
        }
    }

    @ApiOperation("查询当前订单")
    @GetMapping("list/{orderId}")
    public Result list(@PathVariable("orderId") String orderId) {
        List<Orderitem> orderitems = iOrderitemService.selectByOrderId(orderId);
        return Result.ok().data("orderitems",orderitems);
    }




    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("取消订单")
    @GetMapping("sub/{orderid}/{name}")
    public Result sub(@PathVariable("orderid") String orderid,
                      @PathVariable("name") String name
    ) throws Exception {
        System.out.println("NAME是--------------------"+name);
        List<Orderitem> orderitems = iOrderitemService.selectByOrderId(orderid);
        String uid = iOrderService.selectUid(orderid);
        boolean result = iOrderService.removeById(orderid);
        for (Orderitem orderitem : orderitems) {
            LocalDate date = orderitem.getOiSpotdate();
            String spotname = orderitem.getOiSpotname();
            Integer id = iSpotService.findByname(spotname);
            String spottype = orderitem.getOiSpottype();
            Integer num = orderitem.getOiNum();
            Integer oiId = orderitem.getOiId();
            boolean id1 = iOrderitemService.removeById(oiId);
            Integer addnum = iTicketService.addnum(date, id, spottype, num);
            if(addnum==0){
                throw new Exception();
            }
            Integer ticketid = iTicketService.selectBydate(date, id, spottype);
            if(name.equals("cart")) {
                Cart cart = new Cart(0, ticketid, uid, num);
                boolean save = iCartService.save(cart);
                if (save) {
                    System.out.println("取消订单成功，并且加入购物车");
                } else {
                    return Result.error().msg("取消订单失败");
                }
            }



        }
        return Result.ok().msg("取消订单成功");
    }




    @ApiOperation("查找大订单")
    @GetMapping("listAll/{pageNum}/{pageSize}/{uid}")
    public Result listAll(@PathVariable("pageNum") int pageNum,
                          @PathVariable("pageSize") int pageSize,
                          @PathVariable("uid") String uid){
        System.out.println(21111111);
        Page<Order> pageOrder = new Page<>(pageNum,pageSize);
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        System.out.println(11111111);
        System.out.println(uid);
        if(!StringUtils.isEmpty(uid)){
            wrapper.eq("order_userid",uid);
        };
        iOrderService.page(pageOrder,wrapper);
        long total = pageOrder.getTotal();
        List<Order> records = pageOrder.getRecords();
        List<String> strings = new ArrayList<>();
        for(Order order:records){
            String orderId = order.getOrderId();
            List<Orderitem> orderitems = iOrderitemService.selectByOrderId(orderId);
            strings.add(orderitems.get(0).getOiStatus());
        }
        return Result.ok().data("total",total).data("orderlist",records).data("oiStatus",strings);
    }


    @ApiOperation("订单管理(大订单显示)")
    @PostMapping("dadan/{pageNum}/{pageSize}")
    public Result dadan(@ApiParam(value = "当前页码数", required = true) @PathVariable("pageNum") int pageNum,
                        @ApiParam(value = "每页条数", required = true) @PathVariable("pageSize") int pageSize,
                        @RequestBody dingdan ding
    ){
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        System.out.println(ding.getOrderId());
        if(!StringUtils.isEmpty(ding.getOrderId())){
            wrapper.like("order_id",ding.getOrderId());
        }
        Page<Order> pageOrder = new Page<>(pageNum, pageSize);
        Page<Order> page = iOrderService.page(pageOrder,wrapper);
        List<Order> records = page.getRecords();
        List<String> Listid = records.stream().map(Order::getOrderUserid).collect(Collectors.toList());
        QueryWrapper<User> Wrapper = new QueryWrapper<>();
        Wrapper.in("user_id", Listid);
        List<User> list = us.list(Wrapper);
        Map<String, String> map = list.stream().collect(Collectors.toMap(User::getUserId, User::getUserName));
        for (Order a:records) {
            a.setOrderUserid(map.get(a.getOrderUserid()));
        }
        long total = pageOrder.getTotal();
        return Result.ok().msg("订单成功").data("Order",records).data("total",total);
    }
    @ApiOperation("订单管理(小订单显示)")
    @PostMapping("xiaodan/{orderId}")
    public Result xiaodan(@PathVariable("orderId") String orderId
    ){
        QueryWrapper<Orderitem> Wrapper = new QueryWrapper<>();
        Wrapper.eq("oi_orderid", orderId);
        List<Orderitem> list = iOrderitemService.list(Wrapper);
        return Result.ok().msg("订单成功").data("Orderitem",list);
    }
    @ApiOperation("删除订单")
    @PostMapping("shanchu/{orderId}")
    public Result shanchu( @PathVariable("orderId") String orderId
    ){
        boolean b = iOrderService.removeById(orderId);
        return b ? Result.ok().msg("删除成功") : Result.error().msg("删除失败");
    }


    @ApiOperation("查找小订单")
    @GetMapping("listlittleorder/{oid}")
    public Result listlittleorder(@PathVariable("oid") String oid){
        System.out.println("11111111");
         List<Orderitem> orderitems = iOrderitemService.selectByOrderId(oid);
         return Result.ok().data("orderitems",orderitems);
    }





    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("删除订单")
    @GetMapping("deleteorder/{oid}")
    public Result deleteorder(@PathVariable("oid") String oid){
        boolean result = iOrderService.removeById(oid);
        List<Orderitem> orderitems = iOrderitemService.selectByOrderId(oid);
        for (Orderitem orderitem : orderitems) {
            Integer oiId = orderitem.getOiId();
            boolean id1 = iOrderitemService.removeById(oiId);
        }
         return Result.ok().msg("删除订单成功");
    }
    @GetMapping("updateS/{orderid}")
    public Result updateS(@PathVariable("orderid") String orderid){
        UpdateWrapper<Orderitem> wrapper = new UpdateWrapper<Orderitem>();
        wrapper.set("oi_status", 1);
        wrapper.eq("oi_orderid",orderid);
        boolean update = iOrderitemService.update(wrapper);
        return  Result.ok();
    }
}
